var opn = require('opn') // 打开浏览器
var path = require('path') // 路径模块
var express = require('express') // express框架 
var webpack = require('webpack') //核心模块webpack
let chalk = require("chalk");
let ora = require("ora");
var net = require('net')
var package = require('./package.json')

var webpackConfig = require('./webpack.config')// 配置文件
var port = webpackConfig.devServer.port
var app = express()
var compiler = webpack(webpackConfig)
let FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');

var devMiddleware = require('webpack-dev-middleware')(compiler, {
  publicPath: webpackConfig.output.publicPath,
  stats: "errors-only" 
//   quiet: true
})

var hotMiddleware = require('webpack-hot-middleware')(compiler, {
  log: false,
  heartbeat: 2000
})

// compiler.hooks.compile.tap('html-webpack-plugin', function (data, cb) {
//     hotMiddleware.publish({ action: 'reload' })
// })
app.use(require('connect-history-api-fallback')()) 
//开启 支持history路由


app.use(devMiddleware) // 服务器webpack插件


app.use(hotMiddleware) // 热加载自动打包


app.use('/static', express.static('../static'))

var uri = 'http://localhost:' + port

var _resolve
// var readyPromise = new Promise(resolve => {
//   _resolve = resolve
// })


devMiddleware.waitUntilValid(() => {
  let spinner = ora();
  spinner.succeed(chalk.green(`应用已启动:${webpackConfig.devServer.host}:${port}`))
  spinner.succeed(chalk.green('欢迎使用 liu-cli --liuyong'))
  webpackConfig.plugins.push(
    new FriendlyErrorsWebpackPlugin({
      compilationSuccessInfo: {
          messages: [`应用已启动:${webpackConfig.devServer.host}:${port}`],
          notes: ["欢迎使用 liu-cli --liuyong"],
      },
  })
);
  if (process.env.NODE_ENV !== 'testing') {
    opn(uri)
  }
})

var server = app.listen(port,function(){
  let spinner = ora();
  spinner.succeed(chalk.green(`start dev server success`))
})

module.exports = {
  close: () => {
    server.close()
  }
}


